package com.test.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

public class IDCardNumberUtil {

    private static String provinces[] = { "11", "12", "13", "14", "15", "21", "22", "23",
            "31", "32", "33", "34", "35", "36", "37", "41", "42", "43",
            "44", "45", "46", "50", "51", "52", "53", "54", "61", "62",
            "63", "64", "65", "71", "81", "82" };

    private static String citys[] = { "01", "02", "03", "04", "05", "06", "07", "08",
            "09", "10", "21", "22", "23", "24", "25", "26", "27", "28" };

    private static String countys[] = { "01", "02", "03", "04", "05", "06", "07", "08",
            "09", "10", "21", "22", "23", "24", "25", "26", "27", "28",
            "29", "30", "31", "32", "33", "34", "35", "36", "37", "38" };

    public static String getRandomID() {
        StringBuilder identityNo = new StringBuilder();

        // 随机生成省、自治区、直辖市代码 1-2
        identityNo.append(provinces[new Random().nextInt(provinces.length)]);

        // 随机生成地级市、盟、自治州代码 3-4
        identityNo.append(citys[new Random().nextInt(citys.length)]);

        // 随机生成县、县级市、区代码 5-6
        identityNo.append(countys[new Random().nextInt(countys.length)]);

        // 随机生成出生年月 7-14
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date currentDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.YEAR, -new Random().nextInt(61) - 18);  // 18岁到78岁之间
        identityNo.append(dateFormat.format(calendar.getTime()));

        // 随机生成顺序号 15-17
        identityNo.append(String.format("%03d", new Random().nextInt(999)));

        // 生成校验码 18
        identityNo.append(getVerifyCode(identityNo.toString()));
        return identityNo.toString();
    }

    /**
     * 计算校验码
     *
     * @param idNumber
     * @return
     */
    private static char getVerifyCode(String idNumber) {
        int[] weightedFactors = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        char[] verifyCodes = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum += (idNumber.charAt(i) - '0') * weightedFactors[i];
        }
        int remainder = sum % 11;
        return verifyCodes[remainder];
    }

    public static void main(String[] args) {
        String randomID = getRandomID();
        System.out.println(randomID);
        char verifyCode = getVerifyCode("432636199108213318");
        System.out.println(verifyCode);
    }

}